package wxy;

import java.util.ArrayDeque;
import java.util.Deque;

public class LeetCode856 {
    class Solution {
        public int scoreOfParentheses(String s) {
            Deque<Integer> deque = new ArrayDeque<>();
            int n = s.length();
            for (int i = 0; i < n; i++) {
                if (s.charAt(i) == '(') {
                    deque.push(-1);
                } else {
                    if (deque.peek() == -1) {
                        deque.pop();
                    } else {
                        int temp = 0;
                        while (deque.peek() != -1) {
                            temp += deque.pop();
                        }
                        deque.pop();
                        deque.push(temp*2);
                    }
                }
            }
            return deque.stream().reduce(Integer::sum).get();
        }
    }
}
